Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
For event.target in onclick - "Uncaught TypeError TypeError: Cannot set properties of undefined (setting 'value')"

I'm trying to have my html call a javascript function onclick in which the function itself references the event that called it, but I keep getting this error:

Uncaught TypeError TypeError: Cannot set properties of undefined (setting 'value')
    at play (c:\Users\C2Ran\Desktop\Practice\app.js:5:16)
    at onclick (c:\Users\C2Ran\Desktop\Practice\index.html:24:68)

Here's my html:

<!DOCTYPE html>
<head>
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript" src="app.js" defer></script>
</head> 
<body>
    <input type="button" value="X" id="turn" onclick="play(this);">
</body>
</html>

Here's my javascript:

var turn = "X"

function play(event) {
    var cell = event.target;
    cell.value = turn;
    console.log(turn);
    if(turn == "X")
    {
        turn = "O"
    }
    else 
    {
        turn = "X"
    }
}

Is there something I'm missing? Why is it saying value is undefined? Is it not getting the event correctly? Or does onclick not count as an event? I also tried event.currentTarget instead

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Avoid using function calling in HTML attributes, instead use addEventListener,

Your problem is that you are using this when you should be using event.currentTarget

Note: I've improved a bit your code in play() function

function play(cell) {
  cell.value = cell.value === "X" ? "O" : "X"
  console.log(cell.value);
}


document.getElementById('turn').addEventListener('click', e => play(e.currentTarget))
<input type="button" value="X" id="turn">

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda